#include "component/Rigidbody.h"
#include "GameObject.h"
#include "event/Events.h"
#include "physics/IPhysics.h"
#include "physics/Physics.h"


using namespace Boon;


GameObject::RegisterCreationCB<Rigidbody> r;


void Boon::Rigidbody::OnCreate()
{
	m_Flags.reset();
	m_Flags.set( RB_USE_GRAVITY, true );
	m_Constraints = 0; // motion/rotation around all axis

	IMessengerEventStrong eventCreated( new Event_Physics_Rigidbody( *this, Event_Physics_Rigidbody::RB_CREATED ) );
	Messenger::GetInstance().Bang( eventCreated );
	m_Physics = Physics::GetPhysics();
	BOON_ASSERT( m_Physics != nullptr );
}

void Boon::Rigidbody::OnStart()
{

}

void Boon::Rigidbody::OnEnable()
{

}

void Boon::Rigidbody::OnDisable()
{

}

void Boon::Rigidbody::OnDestroy()
{

}

void Boon::Rigidbody::Update()
{
	// Collider has been marked as dirty due to changing members
	if( m_Flags.at( RB_DIRTY ) )
	{
		Shared_ptr<Event_Physics_Rigidbody>e( new Event_Physics_Rigidbody( *this, Event_Physics_Rigidbody::RB_UPDATED ) );
		Messenger::GetInstance().Bang( e );
		m_Flags.set( RB_DIRTY, false );
	}
}

void Boon::Rigidbody::LateUpdate()
{

}


void Boon::Rigidbody::AddForce( const Vector3& force, ForceMode mode )
{
	AddForce( force.x, force.y, force.z, mode );
}

void Boon::Rigidbody::AddForce( float x, float y, float z, ForceMode mode )
{
	m_Physics->AddForce( *this, x, y, z, mode );
}

void Boon::Rigidbody::SetVelocity( const Vector3& velocity )
{
	m_Physics->SetVelocity( GetGameObject().GetUniqueObjectID(), velocity );
}

void Boon::Rigidbody::SetVelocity( float x, float y, float z )
{
	SetVelocity( Vector3( x, y, z ) );
}

const Vector3 Boon::Rigidbody::GetVelocity() const
{
	return m_Physics->GetVelocity( GetGameObject().GetUniqueObjectID() );
}
